<?php

include_once('admin.php');

/**
 * The Catalogue Management class provides functions for managing the catalogue
 */
class catalogue_management extends admin
{
	function __construct()
    {
        // Call the Model constructor
        parent::__construct();
		
		// Load the form helper
		$this->load->helper('form');

		// Load the form validation library
		$this->load->library('form_validation');

		// Load the required models
		$this->load->model('volume_model');
		$this->load->model('author_model');
		$this->load->model('author_volume_model');
		$this->load->model('subject_model');
		$this->load->model('subject_volume_model');
		$this->load->model('loan_model');
		$this->load->model('subscriber_model');
		$this->load->model('location_model');
    }

	/**
	 * Perform a volume search
	 * @param $table The table to be searched
	 * @param $search_by Name of field to do search on
	 * @param $term Term to search for
	 * @param $offset Offset of results (for pagination)
	 */
	public function searchCatalogue($table='tbl_volume', $search_by='title', $term='ALL', $offset = 0)
	{
		// If the user has done a new search
		if ($this->input->post())
		{
			// Get post results and filter them to rid unacceptable characters
			$table = $this->input->post('table');
			$search_by = $this->input->post('search_by');
			$term = preg_replace('/[^a-zA-Z0-9]/', ' ', $this->input->post('term'));
	
			// If the form has been clicked
			redirect('admin/catalogue_management/searchCatalogue/' . $table . '/' . $search_by . '/' . $term );
		}
		
		// Set this page as previous volume search (BUG - searching for a term with > 2 words causes the session data to be lost. I suspect current_url as the culprit)
		$this->session->set_userdata('prev_catalogue_search', preg_replace('[%20]', ' ', current_url()));
		
		// Determine total number of matching results
		if ($table == "tbl_volume")
		{
			$this->data['result_count'] = $this->volume_model->getSearchCount($search_by, $term);
			$this->data['results'] = $this->volume_model->getSearchResults($search_by, $term, $offset, 20);
			
			// Get loan status for the 20 results
			foreach ($this->data['results']->result() as $volume)
				$volume->on_loan = $this->loan_model->getLoanByID($volume->access_id)->num_rows();
			
			$this->data['fields'] = array('access_id'=>'Accession Number', 'call_number'=>'Call Number', 'title'=>'Title', 'catalogue_date'=>'Catalogue Date');
			$this->data['action'] = array('Type'=>'Volume', 'UniqueID'=>'access_id');
		}
		
		else if ($table == "tbl_author")
		{
			$this->data['result_count'] = $this->author_model->getSearchCount($search_by, $term);
			$this->data['results'] = $this->author_model->getSearchResults($search_by, $term, $offset, 20);
			$this->data['fields'] = array('author_id'=>'Author ID', 'author_name'=>'Author Name');
			$this->data['action'] = array('Type'=>'Author', 'UniqueID'=>'author_id');
		}
		
		else if ($table == "tbl_subject")
		{
			$this->data['result_count'] = $this->subject_model->getSearchCount($search_by, $term);
			$this->data['results'] = $this->subject_model->getSearchResults($search_by, $term, $offset, 20);
			$this->data['fields'] = array('subject_id'=>'Subject ID', 'subject_name'=>'Subject Name');
			$this->data['action'] = array('Type'=>'Subject', 'UniqueID'=>'subject_id');
		}
		
		// Setup pagination
		$this->load->library('pagination');
		$config['base_url'] = site_url('admin/catalogue_management/searchCatalogue/' . $table . '/' . $search_by . '/' . $term);
		$config['total_rows'] = $this->data['result_count'];
		$config['per_page'] = 20;
		$config['num_links'] = 7;
		$config['uri_segment'] = 7;
		$this->pagination->initialize($config);
		
		// Load the "view_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/search_catalogue', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}
	
	/**
     * View a volume
	 * @param $access_id Accession Number of Volume to view
     */
	public function viewVolume($access_id)
	{
		// Return the volume that has the specified access_id and then add the volume_table to view
		$this->data['volume'] = $this->volume_model->getVolumeByID( $access_id )->row();
		
		// Return author information for specified volume
		$author_id_array = $this->author_volume_model->getAuthorIDsForVolume( $access_id );
		$this->data['authors'] = $this->author_model->getAuthorsByID( $author_id_array );
		
		// Return subject information for specified volume
		$subject_id_array = $this->subject_volume_model->getSubjectIDsforVolume( $access_id );
		$this->data['subjects'] = $this->subject_model->getSubjectsByID( $subject_id_array );
		
		// Return borrower's subscriber_id from the loan and then get their name
		$this->data['loan'] = $this->loan_model->getSubscriberIDForVolume( $access_id )->row();
		if ( $this->data['loan'] )
		    $this->data['borrower'] = $this->subscriber_model->getSubscriberByID( $this->data['loan']->subscriber_id )->row();

		// Get list of locations
		$this->data['location'] = $this->location_model->getLocation( $this->data['volume']->location_id )->row();
		
		// Load the "view_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/view_volume', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}
	
	/**
     * View an author
	 * @param $author_id Author ID of Author to view
     */
	public function viewAuthor($author_id)
	{
		// Set current page as previous URL
		$this->setThisAsPreviousURL( );
	
		// Return author information
		$this->data['author'] = $this->author_model->getAuthorByID($author_id)->row();
	
		// Return volume information for specified author
		$access_id_array = $this->author_volume_model->getAccessIDsForAuthor( $author_id );
		$this->data['volumes'] = $this->volume_model->getVolumesByID( $access_id_array );
		
		// Load the "view_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/view_author', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}
	
	/**
     * View a subject
	 * @param $subject_id Subject ID of Subject to view
     */
	public function viewSubject($subject_id)
	{
		// Return subject information
		$this->data['subject'] = $this->subject_model->getSubjectByID( $subject_id )->row();		
	
		// Return volume information for specified subject
		$access_id_array = $this->subject_volume_model->getAccessIDsForSubject( $subject_id );
		$this->data['volumes'] = $this->volume_model->getVolumesByID( $access_id_array );
		
		// Load the "view_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/view_subject', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}
	
	/**
     * Add a volume
     */
	public function addVolume()
	{
		// Automatically place Access ID in access_id field
		$this->data['access_id'] = $this->volume_model->getLastAccessID() + 1;
	
		// If 'POST' data exists (i.e. the submit button was clicked)
		if ( $this->input->post() )
		{	
			// If form validation succeeds (All fields correct)
			if ($this->form_validation->run('admin/volume_management'))
			{
				// Get the data to insert
				$data = $this->input->post();
			
				// Update volumes where access_id = $access_id with the values retrieved from the form
				$this->volume_model->addVolume( $data );
			
				redirect('admin/catalogue_management/viewVolume/' . $this->input->post('access_id') );
			}
		}
		
		// Get list of locations
		$this->data['locations'] = $this->location_model->getAllLocations( )->result();
		
		// Load the "add_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/add_volume', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}

	/**
     * Add author to volume
	 * @param $access_id Accession Number of Volume to add author to
     */
	public function addAuthor( $access_id )
	{
		// Setup autocomplete
		$this->data['autocomplete'] = array('author_name'=>'autocomplete/getAuthors');
	
		// If 'POST' data exists (i.e. the submit button was clicked)
		if ( $this->input->post() )
		{
			// Get author name from post
			$author_name = $this->input->post('author_name');
			
			// If author doesn't already exist, create it
			if ( !$this->author_model->getAuthorByName( $author_name )->num_rows() )
				$this->author_model->addAuthor( $author_name);
			
			// Get Author ID of Author
			$author_id = $this->author_model->getAuthorByName( $author_name )->row()->author_id;
	
			// Add author to current volume
			$this->author_volume_model->add($author_id, $access_id);
		}
	
		// Return the volume that has the specified access_id
		$this->data['volume'] = $this->volume_model->getVolumeByID( $access_id )->row();
		
		// Return author information for specified volume
		$author_id_array = $this->author_volume_model->getAuthorIDsForVolume( $access_id );
		$this->data['authors'] = $this->author_model->getAuthorsByID( $author_id_array );
	
		// Load the "add_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/add_author', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);	
	}
	
	/**
     * Add subject to volume
	 * @param $access_id Accession Number of Volume to add subject to
     */
	public function addSubject( $access_id )
	{
		// Setup autocomplete
		$this->data['autocomplete'] = array('subject_name'=>'autocomplete/getSubjects');
	
		// If 'POST' data exists (i.e. the submit button was clicked)
		if ( $this->input->post() )
		{
			// Get subject name from post
			$subject_name = $this->input->post('subject_name');
			
			// If subject doesn't already exist, create it
			if ( !$this->subject_model->getSubjectByName( $subject_name )->num_rows() )
				$this->subject_model->addSubject( $subject_name);
			
			// Get Subject ID of Subject
			$subject_id = $this->subject_model->getSubjectByName( $subject_name )->row()->subject_id;
	
			// Add subject to current volume
			$this->subject_volume_model->add($subject_id, $access_id);
		}
	
		// Return the volume that has the specified access_id
		$this->data['volume'] = $this->volume_model->getVolumeByID( $access_id )->row();
		
		// Return subject information for specified volume
		$subject_id_array = $this->subject_volume_model->getSubjectIDsforVolume( $access_id );
		$this->data['subjects'] = $this->subject_model->getSubjectsByID( $subject_id_array );
	
		// Load the "add_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/add_subject', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}	
	
	/**
     * Modify a volume
	 * @param $access_id Accession Number of Volume to modify
     */
	public function modifyVolume($access_id)
	{
		// If 'POST' data exists (i.e. the submit button was clicked)
		if ( $this->input->post() )
		{
			// Validate input
			$this->form_validation->set_rules('call_number', 'Call Number', 'required');
			$this->form_validation->set_rules('title', 'Title', 'required');
			$this->form_validation->set_rules('location_id', 'Location ID', 'required');
			
			// If form validation succeeds (All fields correct)
			if ($this->form_validation->run())
			{
				// Get form data
				$form_data = $this->input->post();
				
				// Update volume
				$this->volume_model->updateVolume( $access_id, $form_data );
			
				redirect('admin/catalogue_management/viewVolume/' . $form_data['access_id'] );
			}
		}
	
		// Return the volume that has the specified access_id and then add the volume_table to view
		$this->data['volume'] = $this->volume_model->getVolumeByID( $access_id )->row();
		
		// Get list of locations
		$this->data['locations'] = $this->location_model->getAllLocations( )->result();
		
		// Load the "modify_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/modify_volume', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}
	
	/**
     * Modify author
	 * @param $author_id Author ID of author to modify
     */
	public function modifyAuthor($author_id)
	{
		// If 'POST' data exists (i.e. the submit button was clicked)
		if ( $this->input->post() )
		{
			// Validate input
			$this->form_validation->set_rules('author_id', 'Author ID', 'required');
			$this->form_validation->set_rules('author_name', 'Author Name', 'required');
			
			// If form validation succeeds (All fields correct)
			if ($this->form_validation->run())
			{
				// Get form data
				$form_data = $this->input->post();
				
				// Update subject
				$this->author_model->updateAuthor( $author_id, $form_data );
			
				redirect('admin/catalogue_management/viewAuthor/' . $form_data['author_id'] );
			}
		}
	
		// Return author information
		$this->data['author'] = $this->author_model->getAuthorByID($author_id)->row();
	
		// Return volume information for specified author
		$access_id_array = $this->author_volume_model->getAccessIDsForAuthor( $author_id );
		$this->data['volumes'] = $this->volume_model->getVolumesByID( $access_id_array );
		
		// Load the "modify_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/modify_author', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}

	/**
     * Modify subject
	 * @param $subject_id Subject ID of subject to modify
     */
	public function modifySubject($subject_id)
	{
		// If 'POST' data exists (i.e. the submit button was clicked)
		if ( $this->input->post() )
		{
			// Validate input
			$this->form_validation->set_rules('subject_id', 'Subject ID', 'required');
			$this->form_validation->set_rules('subject_name', 'Subject Name', 'required');
			
			// If form validation succeeds (All fields correct)
			if ($this->form_validation->run())
			{
				// Get form data
				$form_data = $this->input->post();
				
				// Update subject
				$this->subject_model->updateSubject( $subject_id, $form_data );
			
				redirect('admin/catalogue_management/viewSubject/' . $form_data['subject_id'] );
			}
		}
	
		// Return subject information
		$this->data['subject'] = $this->subject_model->getSubjectByID( $subject_id )->row();		
	
		// Return volume information for specified subject
		$access_id_array = $this->subject_volume_model->getAccessIDsForSubject( $subject_id );
		$this->data['volumes'] = $this->volume_model->getVolumesByID( $access_id_array );
		
		// Load the "modify_volume" view
		$this->data['main_content'] = $this->load->view('admin/catalogue_management/modify_subject', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}
	
	/**
     * Delete a volume
	 * @param $access_id Accession Number of Volume to delete
     */
	public function deleteVolume($access_id)
	{
		// Delete volume
		$this->volume_model->deleteVolumeByID( $access_id );
	
		// Redirect back to previous search
		redirect( $this->session->userdata('prev_volume_search') );
	}
	
	/**
     * Delete an author
	 * @param $author_id Author ID of author to delete
     */
	public function deleteAuthor($author_id)
	{
		// Delete author
		$this->author_model->deleteAuthorByID( $author_id );
	
		redirect( $this->session->userdata('prev_author_search') );
	}
	
	/**
     * Delete a subject
	 * @param $subject_id Subject ID of subject to delete
     */
	public function deleteSubject($subject_id)
	{
		// Delete subject
		$this->subject_model->deleteSubjectByID( $subject_id );
		
		// Redirect to previous search
		redirect( $this->session->userdata('prev_subject_search') );
	}
	
	/**
     * Removes a subject from a volume
	 * @param $subject_id Subject ID of Subject
	 * @param $access_id Accession Number of Volume to remove subject from
     */
	public function removeSubject($subject_id, $access_id)
	{
		// Remove entry
		$this->subject_volume_model->remove($subject_id, $access_id);
		
		// Redirect to previous page
		redirect( $_SERVER['HTTP_REFERER'] );
	}
	
	/**
     * Removes an author from a volume
	 * @param $author_id Author ID of Author
	 * @param $access_id Accession Number of Volume to remove subject from
     */
	public function removeAuthor($author_id, $access_id)
	{
		// Remove entry
		$this->author_volume_model->remove($author_id, $access_id);
		
		// Redirect to previous page
		redirect( $_SERVER['HTTP_REFERER'] );
	}
}

?>